﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Collections;

namespace BluePortal.Framework
{
    public struct Enum<T> : IEnumerable<T> where T : struct
    {
        public Enum(T value)
        {
            _value = value;
        }
        private T _value;
        public static implicit operator T(Enum<T> e)
        {
            return e._value;
        }
        public static implicit operator Enum<T>(T e)
        {
            return new Enum<T>(e);
        }

        public static implicit operator Enum<T>(string s)
        {
            return new Enum<T>((T)Enum.Parse(typeof(T), s));
        }


        public static Enum<T> FromEnumerable(IEnumerable<T> e)
        {
            int value = 0;
            foreach (T t in e)
            {
                value |= Convert.ToInt32(t);
            }
            return (T)Enum.ToObject(typeof(T), value);
        }

        #region IEnumerable<T> Members
        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            if (!typeof(T).IsSubclassOf(typeof(Enum)))
                throw new Exception("n'est pas un enum");
            int[] allValues = (int[])Enum.GetValues(typeof(T));
            int intValues = Convert.ToInt32(_value);
            foreach (int i in allValues)
            {
                if ((i & intValues) != 0)
                    yield return (T)Enum.ToObject(typeof(T), i);
            }
        }
        #endregion

        #region IEnumerable Members
        IEnumerator IEnumerable.GetEnumerator()
        {
            return (this as IEnumerable<T>).GetEnumerator() as IEnumerator;
        }
        #endregion

        public override string ToString()
        {
            return _value.ToString();
        }
    }
}
